const crypto = require("crypto");
const bcrypt = require("bcrypt");

function decrypt(encryptedPsw, key) {
	let decipher = crypto.createDecipher("aes-256-cbc", key);
	return decipher.update(encryptedPsw, "hex", "utf8") + decipher.final("utf8");
}

module.exports = function (symbolKey) {
	return function (password, cryptedPassword) {
		// sha512
		let shaStr = crypto
			.createHash("sha512")
			.update(password)
			.digest("hex");

		// aes-256-cbc 解密
		let bcryptedPassword = decrypt(cryptedPassword, this[symbolKey]);

		return new Promise((resolve, reject) => {
			bcrypt.compare(shaStr, bcryptedPassword, (err, res) => (err ? reject(err) : resolve(res)));
		});
	};
};
